package com.example.ktapplication.adapter

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.R
import com.example.ktapplication.bean.HotSearchData


class CommomRvAdapter(context: Context, list: List<HotSearchData>, layoutId: Int)
    : RecyclerView.Adapter<CommomRvViewHolder>() {

    lateinit var mContext:Context

    lateinit var mDataList:List<HotSearchData>

    var mLayoutId:Int=0

    init {
        this.mContext=context
        this.mDataList=list
        this.mLayoutId=layoutId
    }

    private var mOnItemClickListener: OnItemClickListener? = null


    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        this.mOnItemClickListener = onItemClickListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommomRvViewHolder {
        val view = View.inflate(mContext, mLayoutId, null)

        return CommomRvViewHolder(view)
    }

    override fun getItemCount(): Int {
        return if (mDataList == null) 0 else mDataList.size
    }

    override fun onBindViewHolder(holder: CommomRvViewHolder, position: Int) {
        val tvHost= holder.itemView.findViewById<TextView>(R.id.tvHost)
        tvHost.text=mDataList[position].name
        setListener(holder, position);
    }


    private fun setListener(holder: CommomRvViewHolder, position: Int) {
        holder.itemView.setOnClickListener { view ->
            if (mOnItemClickListener != null) {
                mOnItemClickListener!!.onItemClick(position)
            }
        }
    }

    fun interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setData(list:List<HotSearchData>){
        mDataList=list
        notifyDataSetChanged()
    }

}

class CommomRvViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    private lateinit var tvHost:TextView

    init {
        tvHost=itemView.findViewById<TextView>(R.id.tvHost)
    }
}